package com.yangye.pisystem.service.impl;

import com.yangye.picommon.enums.PiResultEnum;
import com.yangye.pisystem.domain.SysUser;
import com.yangye.pisystem.dto.SysMenuDTO;
import com.yangye.pisystem.service.SysMenuService;
import com.yangye.pisystem.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yangye on 2019/7/4
 */
@Service
public class PiUserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysMenuService sysMenuService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser sysUser = sysUserService.findByUsername(username);
		if (sysUser == null) {
			throw new UsernameNotFoundException(PiResultEnum.BAD_USERNAME_PASSWORD.getMsg());
		}
		if (StringUtils.equals(sysUser.getStatus(), "0")) {
			throw new DisabledException(PiResultEnum.DISABLED.getMsg());
		}

		// 设置当前用户操作权限
		List<SysMenuDTO> menus = sysMenuService.listMenusByUsername(sysUser.getUsername());
		List<SimpleGrantedAuthority> authorities = new ArrayList<>();
		for (SysMenuDTO menu : menus) {
			if (StringUtils.isNotEmpty(menu.getPermission())) {
				authorities.add(new SimpleGrantedAuthority(menu.getPermission()));
			}
		}

		User user = new User(sysUser.getUsername(), sysUser.getPassword(), authorities);
		return user;
	}
}
